﻿using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using Cloak.Reflection;
using Ruleweaver.Conditions;

namespace Ruleweaver.Annotation
{
	public sealed class MetadataClassConditionSource : IConditionSource
	{
		public MetadataClassConditionSource(Type metadataClassType)
		{
			Contract.Requires(metadataClassType != null);
			Contract.Requires(metadataClassType.IsClass);
			Contract.Requires(metadataClassType.HasAttribute<ConditionsForAttribute>());

			TargetType = metadataClassType.GetAttribute<ConditionsForAttribute>().Type;
			MetadataClassType = metadataClassType;
		}

		#region IConditionSource

		public IEnumerable<Condition> GetConditions()
		{
			return new AnnotatedConditionSource(MetadataClassType)
				.GetConditions()
				.Select(condition => FixClassReferences(condition));
		}
		#endregion

		public Type TargetType { get; private set; }

		public Type MetadataClassType { get; private set; }

		private Condition FixClassReferences(Condition condition)
		{
			return new MetadataClassReferenceFixUp().ChangeToTargetTypeReferences(condition, TargetType);
		}
	}
}